<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import type { Ref } from 'vue'
import {
  CircleCheck,
  Delete,
  Edit,
  User,
  DArrowRight,
  Search,
  Refresh,
  Plus,
  Download
} from '@element-plus/icons-vue'
import { parseTime, baseURL } from '@/utils/validate'
// 引入组件
import Pagination from '@/components/Pagination/Index.vue'
import { UploadProps, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'

import { libraryAdd, libraryDelete, libraryEdit, getLibraryList } from '@/api/admin/product/library'
import { upload, getCommonClassifyList } from '@/api/common'
import { compress } from '@/utils/validate'
// queryForm ref
const queryFormRef = ref<FormInstance>()
/**查询条件 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: ''
})
const classify_option: any = ref([])
const sys_normal_disable = ref([
  { label: '正常', value: '0' },
  { label: '停用', value: '1' }
])
/**表格的loading */
const loading = ref(false)
/**表格数据 */
const dataList: any = ref([])
/**总共条数 */
const total = ref(0)

// 查询产品列表
const getList = () => {
  loading.value = true
  getLibraryList(queryParams.value)
    .then((response: any) => {
      dataList.value = response.rows
      total.value = response.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/**重置数据 */
const resetQuery = () => {
  nextTick(() => {
    // 重置表单
    if (queryFormRef.value) {
      queryFormRef.value?.resetFields()
    }
    handleQuery()
  })
}

/**
 * 非单个禁用
 */
const single = ref(true)
/**
 * 选中多个进行删除
 */
const multiple = ref(true)
/**选中删除的id */
const ids = ref([])

const ruleFormRef = ref<FormInstance>()
const drawer = reactive({
  show: false,
  title: '',
  loading: false,
  form: {
    libraryId: undefined,
    title: '',
    classifyId: '',
    price: 0,
    discountedPrice: 0,
    brand: '',
    model: '',
    specifications: '',
    materialQuality: '',
    features: '',
    cover: '',
    showImg: '',
    status: '0',
    remark: ''
  }
})
interface RuleForm {
  title: string
  cover: string
  classifyId: string
  brand: string
  price: number
  discountedPrice: number
  model: string
  specifications: string
  materialQuality: string
  features: string
  showImg: string
  status: string
  remark: string
}
const rules = reactive<FormRules<RuleForm>>({
  title: [{ required: true, message: '产品标题不能为空', trigger: 'blur' }],
  classifyId: [
    {
      required: true,
      message: '产品分类不能为空',
      trigger: 'change'
    }
  ],
  brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '产品价格不能为空', trigger: 'blur' }],
  discountedPrice: [{ required: true, message: '产品折扣价格不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '产品型号不能为空', trigger: 'blur' }],
  materialQuality: [{ required: true, message: '产品材质不能为空', trigger: 'blur' }],
  features: [{ required: true, message: '产品特性不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }]
})
/**
 * 删除
 */
const handleDelete = (row: any) => {
  const libraryIds = row.libraryId || ids.value
  ElMessageBox.confirm('是否确认删除产品分类编号为"' + libraryIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return libraryDelete(libraryIds)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const handleExport = () => {}

/**
 * 分类状态修改
 */
const handleStatusChange = (row: any) => {
  const text = row.status === '0' ? '启用' : '停用'
  ElMessageBox.confirm('确认要"' + text + '""' + row.title + '"产品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      const params = {
        libraryId: row.libraryId,
        status: row.status
      }
      return libraryEdit(params)
    })
    .then(() => {
      ElMessage.success(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

/**
 * 选择条数
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item?.libraryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

//
const handleAdd = () => {
  ruleFormRef.value?.resetFields()
  drawer.show = true
  drawer.title = '新增产品'
  drawer.form = {
    libraryId: undefined,
    title: '',
    cover: '',
    classifyId: '',
    brand: '',
    price: 0,
    discountedPrice: 0,
    model: '',
    specifications: '',
    materialQuality: '',
    features: '',
    showImg: '',
    status: '0',
    remark: ''
  }
}

/**
 * 修改
 */
const handleUpdate = (row: any) => {
  drawer.show = true
  drawer.title = '修改产品'
  drawer.form = {
    libraryId: row.libraryId,
    title: row.title,
    classifyId: row.classifyId,
    cover: row.cover,
    brand: row.brand,
    price: row.price,
    discountedPrice: row.discountedPrice,
    model: row.model,
    specifications: row.specifications,
    materialQuality: row.materialQuality,
    features: row.features,
    status: row.status,
    showImg: row.showImg,
    remark: row.remark
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  drawer.loading = true
  if (!formEl) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (!drawer.form.libraryId) {
        // 新增
        libraryAdd(drawer.form).then((response: any) => {
          drawer.show = false
          ElMessage.success('新增成功')
          getList()
        })
      } else {
        // 修改
        libraryEdit(drawer.form).then((response: any) => {
          drawer.show = false
          ElMessage.success('修改成功')
          getList()
        })
      }
      drawer.loading = false
    } else {
      console.log('error submit!', fields)
      drawer.loading = false
    }
  })
}

const handleChange: UploadProps['onChange'] = async (uploadFile: any, uploadFiles: any) => {
  // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log('uploadFile, uploadFiles', uploadFile, uploadFiles)
  const { compressFile, compressBase64 }: any = await compress(uploadFile.raw, 50)
  console.log('compressFile, compressBase64', compressFile, compressBase64)
  upload({ name: 'cover_library', base64: compressBase64 }).then((response: any) => {
    console.log('response', response.filePath)
    drawer.form.cover = response.filePath
    //图片上传成功,清除掉对应图片校验结果
    nextTick(() => {
      ruleFormRef.value?.clearValidate('cover')
    })
  })
}
//
const beforeUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('单张图片大小不能超过10MB!')
    return false
  }
  return true
}

const handleShowImgChange: UploadProps['onChange'] = async (uploadFile: any, uploadFiles: any) => {
  // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log('uploadFile, uploadFiles', uploadFile, uploadFiles)
  const { compressFile, compressBase64 }: any = await compress(uploadFile.raw, 50)
  console.log('compressFile, compressBase64', compressFile, compressBase64)
  upload({ name: 'show_img', base64: compressBase64 }).then((response: any) => {
    console.log('response', response.filePath)
    drawer.form.showImg = response.filePath
    //图片上传成功,清除掉对应图片校验结果
    nextTick(() => {
      ruleFormRef.value?.clearValidate('showImg')
    })
  })
}
//
const beforeShowImgUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('单张图片大小不能超过10MB!')
    return false
  }
  return true
}

const getCommon = () => {
  getCommonClassifyList({}).then((response: any) => {
    console.log('resp========', response)
    classify_option.value = response.rows
  })
}
// 初始化列表数据
getList()
// 通用接口
getCommon()
</script>

<template>
  <div class="classify">
    <!-- 条件查询 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="产品名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入产品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="产品状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮组 -->
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain :icon="Edit" :disabled="single" @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="Download" @click="handleExport"> 导出</el-button>
      </el-col>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        key="title"
        label="产品名称"
        align="center"
        prop="title"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="title"
        label="产品分类"
        align="center"
        prop="classifyName"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column key="cover" label="产品封面" width="120" align="center">
        <template #default="{ row }">
          <el-image
            style="width: 80px; height: 80px"
            :src="baseURL() + row.cover"
            fit="cover"
            :preview-src-list="[baseURL() + row.cover]"
            :preview-teleported="true"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        key="title"
        label="品牌"
        align="center"
        prop="brand"
        width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        key="price"
        label="产品价格"
        align="center"
        prop="price"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column key="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        key="createBy"
        label="创建人"
        align="center"
        prop="createBy"
        :show-overflow-tooltip="true"
      />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, null) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        key="remark"
        label="备注"
        align="center"
        prop="remark"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="140"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">
            <el-icon> <edit /> </el-icon>修改
          </el-button>
          <el-button type="primary" link @click="handleDelete(scope.row)">
            <el-icon> <delete /> </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />
    <!-- 新增和修改产品抽屉 -->
    <el-drawer v-model="drawer.show" :title="drawer.title" size="700px">
      <div class="diy-drawer-content">
        <el-form
          ref="ruleFormRef"
          style="max-width: 700px"
          :model="drawer.form"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="title">
                <el-input v-model="drawer.form.title" placeholder="请输入产品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品分类" prop="classifyId">
                <el-select
                  v-model="drawer.form.classifyId"
                  style="width: 100%"
                  placeholder="请选择产品分类"
                  clearable
                >
                  <el-option
                    v-for="(item, k) in classify_option"
                    :key="k"
                    :label="item?.label"
                    :value="item?.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品价格" prop="price">
                <el-input-number
                  v-model="drawer.form.price"
                  class="hide-buttons"
                  :precision="2"
                  :step="0.2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="折扣价格" prop="discountedPrice">
                <el-input-number
                  v-model="drawer.form.discountedPrice"
                  class="hide-buttons"
                  :precision="2"
                  :step="0.1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品品牌" prop="brand">
                <el-input v-model="drawer.form.brand" placeholder="请输入产品品牌"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品型号" prop="model">
                <el-input v-model="drawer.form.model" placeholder="请输入产品型号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品规格">
                <el-input
                  v-model="drawer.form.specifications"
                  placeholder="请输入产品材质"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品材质" prop="materialQuality">
                <el-input
                  v-model="drawer.form.materialQuality"
                  placeholder="请输入产品材质"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产品特性" prop="features">
                <el-input
                  v-model="drawer.form.features"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入产品特性"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产品封面" prop="cover">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleChange"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="drawer.form.cover"
                    :src="baseURL() + drawer.form.cover"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产品细节图片">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleShowImgChange"
                  :before-upload="beforeShowImgUpload"
                >
                  <img
                    v-if="drawer.form.showImg"
                    :src="baseURL() + drawer.form.showImg"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品状态" prop="status">
                <el-radio-group v-model="drawer.form.status">
                  <el-radio value="0" label="0" border>启用</el-radio>
                  <el-radio value="1" label="1" border>停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <!-- todo 这个地方可以换成富文本框 -->
                <el-input
                  v-model="drawer.form.remark"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="diy-drawer-footer">
        <el-button type="primary" :loading="drawer.loading" @click="submit(ruleFormRef)"
          >确 定</el-button
        >
        <el-button @click="drawer.show = false">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss"></style>
